#!/bin/bash

# 最终修复所有剩余的分页问题

echo "开始最终修复所有剩余的分页问题..."
echo "=========================================="

# 定义需要修复的文件列表（除了已经修复的 CouponGroupServiceImpl.java 和 StockServiceImpl.java）
files=(
    "fuint-application/src/main/java/com/fuint/common/service/impl/ArticleServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/CateServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/UserActionServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/SendSmsServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/BookCateServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/MemberGroupServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/BannerServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/DutyServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/StoreServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/UserGradeServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/SettlementServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/ConfirmLogServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/SmsTemplateServiceImpl.java"
    "fuint-application/src/main/java/com/fuint/common/service/impl/BookServiceImpl.java"
)

# 备份文件
echo "创建备份..."
for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        cp "$file" "$file.backup.$(date +%Y%m%d_%H%M%S)"
        echo "已备份: $file"
    fi
done

echo ""
echo "开始修复文件..."

# 修复每个文件
for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        echo "正在修复: $file"
        
        # 使用 Python 脚本进行精确替换
        python3 << 'EOF'
import sys
import re

def fix_pagination_file(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 查找分页方法并修复
        # 匹配分页方法的模式
        pattern = r'(public PaginationResponse<[^>]+> [^(]+\(PaginationRequest paginationRequest\)[^{]*\{[^}]*?)'
        pattern += r'(List<([^>]+)> dataList = ([a-zA-Z0-9_]+)\.selectList\(lambdaQueryWrapper\);)'
        pattern += r'([^}]*?PageRequest pageRequest = PageRequest\.of[^;]*;[^}]*?)'
        pattern += r'(PageImpl pageImpl = new PageImpl\([^;]*;[^}]*?)'
        pattern += r'(PaginationResponse<[^>]+> paginationResponse = new PaginationResponse\([^;]*;[^}]*?)'
        pattern += r'(paginationResponse\.setTotalPages\([^;]*;[^}]*?)'
        pattern += r'(paginationResponse\.setTotalElements\([^;]*;[^}]*?)'
        pattern += r'(paginationResponse\.setContent\([^;]*;[^}]*?)'
        pattern += r'(return paginationResponse;[^}]*?\})'
        
        # 简化的替换策略：直接查找和替换关键行
        # 1. 替换 selectList 行
        content = re.sub(
            r'(\s+)List<([^>]+)> dataList = ([a-zA-Z0-9_]+)\.selectList\(lambdaQueryWrapper\);',
            r'\1Page<\2> page = new Page<>(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());\n\1Page<\2> pageResult = \3.selectPage(page, lambdaQueryWrapper);\n\1List<\2> dataList = pageResult.getRecords();',
            content
        )
        
        # 2. 删除错误的 PageRequest 和 PageImpl 行
        content = re.sub(r'\s+PageRequest pageRequest = PageRequest\.of[^;]*;\n', '', content)
        content = re.sub(r'\s+PageImpl pageImpl = new PageImpl[^;]*;\n', '', content)
        
        # 3. 修复 PaginationResponse 构造和设置
        content = re.sub(r'new PaginationResponse\(pageImpl,', 'new PaginationResponse(pageResult,', content)
        content = re.sub(r'\s+paginationResponse\.setTotalPages\([^;]*;\n', '', content)
        content = re.sub(r'\s+paginationResponse\.setTotalElements\([^;]*;\n', '', content)
        content = re.sub(r'\s+paginationResponse\.setContent\([^;]*;\n', '', content)
        
        # 4. 替换复杂的返回语句为简单的 PaginationHelper 调用
        content = re.sub(
            r'(\s+)PaginationResponse<([^>]+)> paginationResponse = new PaginationResponse\(pageResult, \2\.class\);\s*return paginationResponse;',
            r'\1return PaginationHelper.convertToPaginationResponse(dataList, (int)pageResult.getCurrent(), (int)pageResult.getSize(), pageResult.getTotal(), \2.class);',
            content
        )
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content)
        
        return True
    except Exception as e:
        print(f"Error processing {filename}: {e}")
        return False

# 处理文件
filename = sys.argv[1] if len(sys.argv) > 1 else ""
if filename:
    success = fix_pagination_file(filename)
    sys.exit(0 if success else 1)
EOF
        
        # 调用 Python 脚本
        if python3 -c "
import sys
import re

def fix_pagination_file(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 1. 替换 selectList 行
        content = re.sub(
            r'(\s+)List<([^>]+)> dataList = ([a-zA-Z0-9_]+)\.selectList\(lambdaQueryWrapper\);',
            r'\1Page<\2> page = new Page<>(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());\n\1Page<\2> pageResult = \3.selectPage(page, lambdaQueryWrapper);\n\1List<\2> dataList = pageResult.getRecords();',
            content
        )
        
        # 2. 删除错误的 PageRequest 和 PageImpl 行
        content = re.sub(r'\s+PageRequest pageRequest = PageRequest\.of[^;]*;\n', '', content)
        content = re.sub(r'\s+PageImpl pageImpl = new PageImpl[^;]*;\n', '', content)
        
        # 3. 修复 PaginationResponse 构造和设置
        content = re.sub(r'new PaginationResponse\(pageImpl,', 'new PaginationResponse(pageResult,', content)
        content = re.sub(r'\s+paginationResponse\.setTotalPages\([^;]*;\n', '', content)
        content = re.sub(r'\s+paginationResponse\.setTotalElements\([^;]*;\n', '', content)
        content = re.sub(r'\s+paginationResponse\.setContent\([^;]*;\n', '', content)
        
        # 4. 替换复杂的返回语句为简单的 PaginationHelper 调用
        content = re.sub(
            r'(\s+)PaginationResponse<([^>]+)> paginationResponse = new PaginationResponse\(pageResult, \2\.class\);\s*return paginationResponse;',
            r'\1return PaginationHelper.convertToPaginationResponse(dataList, (int)pageResult.getCurrent(), (int)pageResult.getSize(), pageResult.getTotal(), \2.class);',
            content
        )
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content)
        
        return True
    except Exception as e:
        print(f'Error processing {filename}: {e}')
        return False

success = fix_pagination_file('$file')
sys.exit(0 if success else 1)
"; then
            echo "  ✅ 修复完成"
        else
            echo "  ❌ 修复失败"
        fi
    else
        echo "  ❌ 文件不存在: $file"
    fi
done

echo ""
echo "修复完成！"
echo "=========================================="
echo "请运行以下命令验证修复结果："
echo "bash check_selectlist_in_pagination.sh"
